/**
 * 子应用处理消息，跳转路由
 *
 */
import { useWujieStore } from '@/store/wujie';
import { useUserStore } from '@/store/user';
import { addMicroAppRoute } from '@/router/generator-routers';

/**
 * 子应用绑定事件监听器
 * @param instance
 * @param router
 */
export function bindMicroAppEvents(instance, router) {
  handleMicroMsg(instance, router);
}
/**
 * 子应用绑定事件监听器
 * @deprecated
 * @see bindMicroAppEvents
 * @param instance
 * @param router
 */
export function handleMicroMsg(instance, router) {
  // 初始化avic_apps
  const wujieStore = useWujieStore();
  wujieStore.SET_AVIC_APPS([]);
  const props = window.$wujie?.props;
  // 初始化子应用token，用户和 权限信息
  if (!wujieStore.permissions) {
    wujieStore.GENERATE_ROUTES_DYNAMIC(props.permissions);
  }
  // 监听主应用的消息
  window?.$wujie?.bus.$on(props.appName, (params) => {
    switch (params.action) {
      case 'router-change':
        {
          /* 缓存数据，用于keepalive使用 */
          let apps = wujieStore.AVIC_APPS;
          apps = !apps ? [] : apps;
          const item = apps.find((data) => data.name === params.data.name);
          // 子应用需要根据传递过来的参数 自行注册路由再打开（需求点：子应用打开子应用的页签）
          if (params.data.meta.microAppRequiredAddroute && params.data.path) {
            addMicroAppRoute(params.data, router);
          }
          if (params.data.path) {
            if (!item) {
              apps.push({ ...params.data, path: params.data.path });
              wujieStore.SET_AVIC_APPS(apps);
            }
            router.push({ path: params.data.path, query: { ...params.query } });
          } else {
            const componentUrl = params.data.meta.microAppSubComponent;
            const currentRouter = wujieStore.componentMapRouter[componentUrl];
            // 找到组件路由
            const path = currentRouter.path || '/exception/404';

            if (!item) {
              apps.push({ ...params.data, path });
              wujieStore.SET_AVIC_APPS(apps);
            }
            router.push({ path, query: { ...params.query } });
          }
        }
        break;
      case 'router-remove':
        {
          /* 删除本地存储，如果子应用不是预加载和预执行的APP，需要清除一下 */
          let index = -1;
          const apps = wujieStore.AVIC_APPS;
          apps.find((data, i) => {
            if (data.name === params.data.name) {
              index = i;
            }
            return index !== -1;
          });
          if (index !== -1) {
            apps.splice(index, 1);
            wujieStore.SET_AVIC_APPS(apps);
          }
          // 关闭页签时跳转路由到空白页面
          if (apps.length === 0) {
            router.push({ path: '/microAppHome' });
          }
          // 查找path
          let path = null;
          if (params.data.path) {
            path = params.data.path;
          } else {
            // 子应用组件路径存在，则根据路径找出path 推路由
            // 根据映射找到组件相关路由
            const componentUrl = params.data.meta.microAppSubComponent;
            const currentRouter = wujieStore.componentMapRouter[componentUrl];

            // 找到组件路由
            path = currentRouter ? currentRouter.path : '/exception/404';
          }
          // 清除路由缓存
          if (window.clearMicroCache) {
            window.clearMicroCache(path);
          }
        }
        break;
      case 'router-push':
        {
          const routeExists = router.getRoutes().some((route) => route.path === params.path);
          if (!routeExists) {
            instance.$warning('跳转的路由不存在');
            return;
          }
          // 子应用切换当前页页签路由
          router.push({
            path: params.path,
            query: { ...params.query }
          });
        }
        break;
      case 'skin-change':
        {
          // 皮肤切换
          if (params.data.skin) {
            wujieStore.UPDATE_SKIN(params.data.skin);
          }
        }
        break;
      case 'tab-refresh': {
        // 刷新页签
        let path = null;
        if (params.data.path) {
          path = params.data.path;
        } else {
          // 子应用组件路径存在，则根据路径找出path 推路由
          // 根据映射找到组件相关路由
          const componentUrl = params.data.meta.microAppSubComponent;
          const currentRouter = wujieStore.componentMapRouter[componentUrl];

          // 找到组件路由
          path = currentRouter ? currentRouter.path : '/exception/404';
        }
        // 刷新路由
        if (window.refreshMicroTab) {
          setTimeout(() => {
            window.refreshMicroTab(path);
          }, 300);
        }
        break;
      }
      default:
        break;
    }
  });
  window?.$wujie?.bus.$on('token-refresh', (params) => {
    const userStore = useUserStore();
    userStore.SET_TOKEN(params.accessToken, params.refreshToken);
  });
}

/**
 * 移除微应用所有事件监听器
 * @deprecated
 * @see unbindMicroAppEvents
 */
export function handleOffAllMicroMsg() {
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  window?.$wujie?.bus.$offAll(() => {});
}

/**
 * 移除微应用所有事件监听器
 */
export function unbindMicroAppEvents() {
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  window?.$wujie?.bus.$offAll(() => {});
}
